package com.ruoyi.front;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.ijpay.core.enums.SignType;
import com.ijpay.core.enums.TradeType;
import com.ijpay.core.kit.HttpKit;
import com.ijpay.core.kit.IpKit;
import com.ijpay.core.kit.QrCodeKit;
import com.ijpay.core.kit.WxPayKit;
import com.ijpay.wxpay.WxPayApi;
import com.ijpay.wxpay.WxPayApiConfig;
import com.ijpay.wxpay.WxPayApiConfigKit;
import com.ijpay.wxpay.model.UnifiedOrderModel;
import com.jfinal.kit.StrKit;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMember;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.config.WxPayBean;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

@Controller
public class pay extends AbstractWxPayApiController  {

    @Autowired
    private WxPayBean wxPayBean;
    //站点信息
    @Autowired
    private ISysSiteService iSysSiteService;
    @Autowired
    private ISysDownorderService iSysDownorderService;
    @Autowired
    private ISysGlodpotService iSysGlodpotService;
    @Autowired
    private ISysTradesetService iSysTradesetService;
    @Autowired
    private ISysDocService iSysDocService;
    @Autowired
    private  ISysMemberService iSysMemberService;
    @Autowired
    private  ISysTopicorderService iSysTopicorderService;
    @Autowired
    private ISysTopicService iSysTopicService;
    @Autowired
    private ISysVgroupService iSysVgroupService;
    @Autowired
    private ISysViporderService iSysViporderService;
    @Autowired
    private ISysGlodorderService iSysGlodorderService;
    @Autowired
    private ISysGroupService iSysGroupService;
    @Autowired
    private ISysWeixinsetService iSysWeixinsetService;
    @Autowired
    private ServerConfig serverConfig;
    private String notifyUrl;
    private String refundNotifyUrl;
    private static final String USER_PAYING = "USERPAYING";


    @Override
    public WxPayApiConfig getApiConfig() {
        SysWeixinset  sysWeixinset = new SysWeixinset();
        sysWeixinset = iSysWeixinsetService.selectSysWeixinsetById(1);
        JSONObject jsonObject = JSON.parseObject(sysWeixinset.getValue());
        WxPayApiConfig apiConfig;
        String domain = serverConfig.getUrl();
        try {
            //apiConfig = WxPayApiConfigKit.getApiConfig(wxPayBean.getAppId());
            apiConfig = WxPayApiConfigKit.getApiConfig(jsonObject.getString("WAPPID"));
        } catch (Exception e) {
            /*apiConfig = WxPayApiConfig.builder()
                    .appId(wxPayBean.getAppId())
                    .mchId(wxPayBean.getMchId())
                    .partnerKey(wxPayBean.getPartnerKey())
                    .certPath(wxPayBean.getCertPath())
                    .domain(wxPayBean.getDomain())
                    .build();*/
            apiConfig = WxPayApiConfig.builder()
                    .appId(jsonObject.getString("WAPPID"))
                    .mchId(jsonObject.getString("MCHID"))
                    .partnerKey(jsonObject.getString("WXKEY"))
                    .certPath(wxPayBean.getCertPath())
                    .domain(domain)
                    .build();

        }
        //notifyUrl = apiConfig.getDomain().concat("/payNotify");
        //refundNotifyUrl = apiConfig.getDomain().concat("/wxPay/refundNotify");
        notifyUrl = domain.concat("/payNotify");
        refundNotifyUrl = domain.concat("/wxPay/refundNotify");
        return apiConfig;
    }
    @RequestMapping( {"/scancode1"})
    @ResponseBody
    public AjaxResult scanCode1(HttpServletRequest request, HttpServletResponse response,
                                @RequestParam("productId") String productId) {
        try {
            if (StrKit.isBlank(productId)) {
                return  AjaxResult.error("productId is null");
            }
            WxPayApiConfigKit.putApiConfig(getApiConfig());
            WxPayApiConfig config = WxPayApiConfigKit.getWxPayApiConfig();
            //获取扫码支付（模式一）url
            String qrCodeUrl = WxPayKit.bizPayUrl(config.getPartnerKey(), config.getAppId(), config.getMchId(), productId);
            //生成二维码保存的路径
            String name = "payQRCode1.png";
            boolean encode = QrCodeKit.encode(qrCodeUrl, BarcodeFormat.QR_CODE, 3, ErrorCorrectionLevel.H,
                    "png", 200, 200,
                    ResourceUtils.getURL("classpath:").getPath().concat("static").concat(File.separator).concat(name));
            if (encode) {
                //在页面上显示
                return AjaxResult.success(name);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return  AjaxResult.error("系统异常：" + e.getMessage());
        }
        return null;
    }
    /**
     * 扫码支付模式二
     */
    @RequestMapping(value = "/scanCode2", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public void scanCode2(HttpServletRequest request, HttpServletResponse response,
                                @RequestParam("total_fee") String totalFee,@RequestParam("docid") long docid,@RequestParam("type") String type,@RequestParam("readdown") String readdown) throws IOException {

        if (StrKit.isBlank(totalFee)) {
            //return  AjaxResult.error("支付金额不能为空");
        }
        String price = totalFee;
        BigDecimal bigDecimalfee = new BigDecimal(totalFee);
        bigDecimalfee = bigDecimalfee.multiply(new BigDecimal(100));
        totalFee =String.valueOf(bigDecimalfee.intValue());
        String ip = IpKit.getRealIp(request);
        if (StrKit.isBlank(ip)) {
            ip = "127.0.0.1";
        }
        int userid = -1;
        //产生随机数
        if(ShiroUtils.getSubject().getPrincipal() == null) {
            Random random = new Random();
            int min = -99999999;
            int max = -10000000;
            userid = random.nextInt(max - min + 1) + min;
            if (StringUtils.getCookie(request, "userid").isEmpty()) {
                response.addCookie(new Cookie("userid", String.valueOf(userid)));
            } else {
                userid = Integer.valueOf(StringUtils.getCookie(request, "userid"));
            }
        }else
        {
             userid = ShiroUtils.getSysMember().getUserid().intValue();
        }
        // 生成随机数
        List<SysSite> sysSiteList =  iSysSiteService.selectSysSiteList(new SysSite());
        String sitename = sysSiteList.get(0).getName()+"-付款["+price+"元]";
        String attachname = type +"|"+ readdown + "|"+userid+"|"+ docid;
        WxPayApiConfigKit.putApiConfig(getApiConfig());
        WxPayApiConfig wxPayApiConfig = WxPayApiConfigKit.getWxPayApiConfig();
        Map<String, String> params = UnifiedOrderModel
                .builder()
                .appid(wxPayApiConfig.getAppId())
                .mch_id(wxPayApiConfig.getMchId())
                .nonce_str(WxPayKit.generateStr())
                .body(sitename)
                .attach(attachname)
                .out_trade_no(WxPayKit.generateStr())
                .total_fee(totalFee)
                .spbill_create_ip(ip)
                .notify_url(notifyUrl)
                .trade_type(TradeType.NATIVE.getTradeType())
                .build()
                .createSign(wxPayApiConfig.getPartnerKey(), SignType.HMACSHA256);

        String xmlResult = WxPayApi.pushOrder(false, params);
        System.out.println("统一下单:" + xmlResult);

        Map<String, String> result = WxPayKit.xmlToMap(xmlResult);

        String returnCode = result.get("return_code");
        String returnMsg = result.get("return_msg");
        System.out.println(returnMsg);
        if (!WxPayKit.codeIsOk(returnCode)) {
            //return  AjaxResult.error("error:" + returnMsg);
        }
        String resultCode = result.get("result_code");
        if (!WxPayKit.codeIsOk(resultCode)) {
            //return AjaxResult.error("error:" + returnMsg);
        }
        //生成预付订单success

        String qrCodeUrl = result.get("code_url");
        String name = "pay.png";
        String savedir = ResourceUtils.getURL("classpath:").getPath().concat("static").concat(File.separator).concat(name);
        boolean encode = QrCodeKit.encode(qrCodeUrl, BarcodeFormat.QR_CODE, 3, ErrorCorrectionLevel.H, "png", 200, 200,
                savedir);
        if (encode) {

            //在页面上显示
            //return AjaxResult.success(name);
            //显示支付图片流
            response.setContentType("image/jpeg");
            response.setCharacterEncoding("UTF-8");

            // 读取图片文件到BufferedImage
            BufferedImage image = ImageIO.read(new File(savedir));

            // 获取输出流
            ServletOutputStream outStream = response.getOutputStream();

            // 写入图片到输出流
            ImageIO.write(image, "jpg", outStream);
        }
        //return null;
    }
    //vip扫码支付
    @RequestMapping(value = "/weipay.html", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public void weipay(HttpServletRequest request, HttpServletResponse response,
                          @RequestParam("vgroupid") Long vgroupid) throws IOException {
        String ip = IpKit.getRealIp(request);
        if (StrKit.isBlank(ip)) {
            ip = "127.0.0.1";
        }
        SysVgroup vipgroup = iSysVgroupService.selectSysVgroupByVgroupid(vgroupid);
        int userid = ShiroUtils.getSysMember().getUserid().intValue();
        List<SysSite> sysSiteList =  iSysSiteService.selectSysSiteList(new SysSite());
        String totalFee = vipgroup.getCash2();
        BigDecimal bigDecimalfee = new BigDecimal(totalFee);
        bigDecimalfee = bigDecimalfee.multiply(new BigDecimal(100));
        totalFee =String.valueOf(bigDecimalfee.intValue());
        String sitename = sysSiteList.get(0).getName()+"-开通["+vipgroup.getVgroupname()+"]";
        String readdown = "vip";
        String attachname = "vip|"+ readdown + "|"+userid+"|"+ vgroupid;
        WxPayApiConfigKit.putApiConfig(getApiConfig());
        WxPayApiConfig wxPayApiConfig = WxPayApiConfigKit.getWxPayApiConfig();
        Map<String, String> params = UnifiedOrderModel
                .builder()
                .appid(wxPayApiConfig.getAppId())
                .mch_id(wxPayApiConfig.getMchId())
                .nonce_str(WxPayKit.generateStr())
                .body(sitename)
                .attach(attachname)
                .out_trade_no(WxPayKit.generateStr())
                .total_fee(totalFee)
                .spbill_create_ip(ip)
                .notify_url(notifyUrl)
                .trade_type(TradeType.NATIVE.getTradeType())
                .build()
                .createSign(wxPayApiConfig.getPartnerKey(), SignType.HMACSHA256);

        String xmlResult = WxPayApi.pushOrder(false, params);
        System.out.println("统一下单:" + xmlResult);

        Map<String, String> result = WxPayKit.xmlToMap(xmlResult);

        String returnCode = result.get("return_code");
        String returnMsg = result.get("return_msg");
        System.out.println(returnMsg);
        if (!WxPayKit.codeIsOk(returnCode)) {
            //return  AjaxResult.error("error:" + returnMsg);
        }
        String resultCode = result.get("result_code");
        if (!WxPayKit.codeIsOk(resultCode)) {
            //return AjaxResult.error("error:" + returnMsg);
        }
        //生成预付订单success

        String qrCodeUrl = result.get("code_url");
        String name = "payvip.png";
        String savedir = ResourceUtils.getURL("classpath:").getPath().concat("static").concat(File.separator).concat(name);
        boolean encode = QrCodeKit.encode(qrCodeUrl, BarcodeFormat.QR_CODE, 3, ErrorCorrectionLevel.H, "png", 200, 200,
                savedir);
        if (encode) {

            //在页面上显示
            //return AjaxResult.success(name);
            //显示支付图片流
            response.setContentType("image/jpeg");
            response.setCharacterEncoding("UTF-8");

            // 读取图片文件到BufferedImage
            BufferedImage image = ImageIO.read(new File(savedir));

            // 获取输出流
            ServletOutputStream outStream = response.getOutputStream();

            // 写入图片到输出流
            ImageIO.write(image, "jpg", outStream);
        }
        //return null;
    }
    //充值扫码支付
    @RequestMapping(value = "/weipay2.html", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public void weipay2(HttpServletRequest request, HttpServletResponse response,
                       @RequestParam("cash") String cash) throws IOException {
        String ip = IpKit.getRealIp(request);
        if (StrKit.isBlank(ip)) {
            ip = "127.0.0.1";
        }
        int userid = ShiroUtils.getSysMember().getUserid().intValue();
        List<SysSite> sysSiteList =  iSysSiteService.selectSysSiteList(new SysSite());
        String totalFee = cash;
        BigDecimal bigDecimalfee = new BigDecimal(totalFee);
        bigDecimalfee = bigDecimalfee.multiply(new BigDecimal(100));
        totalFee =String.valueOf(bigDecimalfee.intValue());
        String sitename = sysSiteList.get(0).getName()+"-充值["+cash+"]";
        String readdown = "glod";
        String attachname = "glod|"+ readdown + "|"+userid+"|"+ cash;
        WxPayApiConfigKit.putApiConfig(getApiConfig());
        WxPayApiConfig wxPayApiConfig = WxPayApiConfigKit.getWxPayApiConfig();
        Map<String, String> params = UnifiedOrderModel
                .builder()
                .appid(wxPayApiConfig.getAppId())
                .mch_id(wxPayApiConfig.getMchId())
                .nonce_str(WxPayKit.generateStr())
                .body(sitename)
                .attach(attachname)
                //.out_trade_no(WxPayKit.generateStr())
                .out_trade_no(DateUtil.format(new Date(), "yyyyMMddHHmmss"))
                .total_fee(totalFee)
                .spbill_create_ip(ip)
                .notify_url(notifyUrl)
                .trade_type(TradeType.NATIVE.getTradeType())
                .build()
                .createSign(wxPayApiConfig.getPartnerKey(), SignType.HMACSHA256);

        String xmlResult = WxPayApi.pushOrder(false, params);
        System.out.println("统一下单:" + xmlResult);

        Map<String, String> result = WxPayKit.xmlToMap(xmlResult);

        String returnCode = result.get("return_code");
        String returnMsg = result.get("return_msg");
        System.out.println(returnMsg);
        if (!WxPayKit.codeIsOk(returnCode)) {
            //return  AjaxResult.error("error:" + returnMsg);
        }
        String resultCode = result.get("result_code");
        if (!WxPayKit.codeIsOk(resultCode)) {
            //return AjaxResult.error("error:" + returnMsg);
        }
        //生成预付订单success

        String qrCodeUrl = result.get("code_url");
        String name = "payglod.png";
        String savedir = ResourceUtils.getURL("classpath:").getPath().concat("static").concat(File.separator).concat(name);
        boolean encode = QrCodeKit.encode(qrCodeUrl, BarcodeFormat.QR_CODE, 3, ErrorCorrectionLevel.H, "png", 200, 200,
                savedir);
        if (encode) {

            //在页面上显示
            //return AjaxResult.success(name);
            //显示支付图片流
            response.setContentType("image/jpeg");
            response.setCharacterEncoding("UTF-8");

            // 读取图片文件到BufferedImage
            BufferedImage image = ImageIO.read(new File(savedir));

            // 获取输出流
            ServletOutputStream outStream = response.getOutputStream();

            // 写入图片到输出流
            ImageIO.write(image, "jpg", outStream);
        }
        //return null;
    }
    /**
     * 异步通知
     */
    @RequestMapping(value = "/payNotify", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String payNotify(HttpServletRequest request,HttpServletResponse response) {
        String xmlMsg = HttpKit.readData(request);
        System.out.println("支付通知=" + xmlMsg);
        Map<String, String> params = WxPayKit.xmlToMap(xmlMsg);

        String returnCode = params.get("return_code");


        // 注意重复通知的情况，同一订单号可能收到多次通知，请注意一定先判断订单状态
        // 注意此处签名方式需与统一下单的签名类型一致
        if (WxPayKit.verifyNotify(params, WxPayApiConfigKit.getWxPayApiConfig().getPartnerKey(), SignType.HMACSHA256)) {
            if (WxPayKit.codeIsOk(returnCode)) {

                // 更新订单信息
                // 发送通知等
                String attach = params.get("attach");
                String[] parts = attach.split("\\|");
                String total_fee = params.get("total_fee");
                BigDecimal mount =  new BigDecimal(total_fee);
                mount = mount.divide(new BigDecimal(100));
                //String totalfee =String.valueOf(mount);
                String cash =String.valueOf(mount);
                String trade_no = params.get("transaction_id");
                //设置cookie //有待更好的方法
                /*if (StringUtils.getCookie(request,"userid").isEmpty()) {
                    response.addCookie(new Cookie("userid", parts[1]));
                }*/
                String title = "文档阅读";
                String readdown = parts[1];
                if("downpay".equals(readdown))
                    title = "文档下载";

                //System.out.println("cookie="+StringUtils.getCookie(request,"userid"));
                //结束
                String out_trade_no = params.get("out_trade_no");
                Long userid = Long.parseLong(parts[2]);

                //类型(文档还是专题)
                String type = parts[0];
                String which = type+readdown;
                Long id = 0l;
                if(!"glod".equals(type))
                    id = Long.parseLong(parts[3]);
                if(parts.length==4)
                {
                    if("docreadpay".equals(which) || "docdownpay".equals(which) ) //文档阅读
                        docdown(out_trade_no,title,"1",userid,id,cash,mount,trade_no,1,readdown);
                    if("topicdownpay".equals(which)) //专题下载
                        topicdown(out_trade_no,"专题下载","1",userid,id,cash,mount,trade_no,1);
                    if("vipvip".equals(which)) //开通vip
                        vipopen(out_trade_no,"开通","1",userid,id,cash,mount,trade_no,1,readdown);
                    if("glodglod".equals(which))
                        cashglod(out_trade_no,"充值","1",userid,id,cash,mount,trade_no,1,readdown);
                }

                Map<String, String> xml = new HashMap<String, String>(2);
                xml.put("return_code", "SUCCESS");
                xml.put("return_msg", "OK");
                return WxPayKit.toXml(xml);
            }
        }
        return null;
    }
    //充值
    private  void cashglod(String out_trade_no,String title,String from,Long userid,Long id,String cash,BigDecimal mount,String trade_no,Integer state,String readdown)
    {

        if(iSysGlodorderService.selectSysGlodorderByOrderid(out_trade_no)==null)//判断订单是否已存在
        {
            SysGlodorder sysDownorder = new SysGlodorder();
            sysDownorder.setOrderid(out_trade_no);
            sysDownorder.setTitle(title);
            sysDownorder.setFrom(1);
            sysDownorder.setUserid(userid);
            sysDownorder.setCash(cash);
            sysDownorder.setGlods(Float.parseFloat(cash));
            sysDownorder.setTradeno(trade_no);
            sysDownorder.setState(1);
            iSysGlodorderService.insertSysGlodorder(sysDownorder);
            //插入记录
            SysGlodpot sysGlodpot = new SysGlodpot();
            sysGlodpot.setUserid(userid);
            sysGlodpot.setLinkid(Long.parseLong(out_trade_no));
            sysGlodpot.setType(10l);
            sysGlodpot.setGlods(mount);
            iSysGlodpotService.insertSysGlodpot(sysGlodpot);
            //更新用户的账户金额
            iSysMemberService.updateGlod(userid, mount);
        }
    }
    //开通vip
    private  void vipopen(String out_trade_no,String title,String from,Long userid,Long id,String cash,BigDecimal mount,String trade_no,Integer state,String readdown)
    {
        SysVgroup sysVgroup = iSysVgroupService.selectSysVgroupByVgroupid(id);
        SysViporder sysDownorder = new SysViporder();
        sysDownorder.setOrderid(out_trade_no);
        sysDownorder.setTitle(title+sysVgroup.getVgroupname());
        sysDownorder.setFrom(1);
        sysDownorder.setUserid(userid);
        sysDownorder.setVgroupid(id);
        sysDownorder.setCash(cash);
        sysDownorder.setTradeno(trade_no);
        sysDownorder.setState(1);
        iSysViporderService.insertSysViporder(sysDownorder);

        SysMember user = iSysMemberService.selectSysMemberByUserid(userid);
        Date vipdate = new Date();
        if(user.getVipdate()!=null && DateUtil.compare(user.getVipdate(),DateUtil.date())>0)
        {
            vipdate = DateUtil.offsetDay(user.getVipdate(),sysVgroup.getVipdays().intValue());
        }
        else
        {
            vipdate = DateUtil.offsetDay(DateUtil.date(),sysVgroup.getVipdays().intValue());
        }
        //更新vip用户
        SysMember sysMember = new SysMember();
        sysMember.setUserid(userid);
        sysMember.setVipdate(vipdate);
        sysMember.setVgroupid(id);
        iSysMemberService.updateSysMember(sysMember);
        //更新vip天数
    }


    //有点不合理哦，暂时就这么干吧
    //文档，下载，奖励
    private  void docdown(String out_trade_no,String title,String from,Long userid,Long id,String cash,BigDecimal mount,String trade_no,Integer state,String readdown)
    {
        SysDownorder sysDownorder = new SysDownorder();
        sysDownorder.setOrderid(out_trade_no);
        sysDownorder.setTitle(title);
        sysDownorder.setFrom("1");
        sysDownorder.setUserid(userid);
        sysDownorder.setDocid(id);
        sysDownorder.setCash(cash);
        sysDownorder.setTradeno(trade_no);
        sysDownorder.setReaddown(readdown);
        sysDownorder.setState(1);
        iSysDownorderService.insertSysDownorder(sysDownorder);
        List<SysTradeset> sysTradesets = iSysTradesetService.selectSysTradesetList(new SysTradeset());
        SysDoc sysDoc = iSysDocService.selectSysDocByDocid(id);
        if(sysTradesets.size()>0&&sysTradesets.get(0).getToauth2()>0) {
            SysGlodpot glodpot = new SysGlodpot();

            glodpot.setUserid(sysDoc.getUserid()); //付给文档作者的
            glodpot.setLinkid(id);

            glodpot.setGlods(mount.multiply(BigDecimal.valueOf(1 - sysTradesets.get(0).getRate())));
            glodpot.setType("readpay".equals(readdown) ? 32l : 42l);
            iSysGlodpotService.insertSysGlodpot(glodpot);
            iSysMemberService.updateGlod(sysDoc.getUserid(), mount.multiply(BigDecimal.valueOf(1 - sysTradesets.get(0).getRate())));
        }
        SysGlodpot glodpot = new SysGlodpot();
        glodpot.setUserid(userid);
        glodpot.setLinkid(id);

        glodpot.setGlods(BigDecimal.ZERO.subtract(mount));
        glodpot.setType("readpay".equals(readdown) ? -32l : -42l);
        iSysGlodpotService.insertSysGlodpot(glodpot);
        //更新文档作者奖励
    }
    private  void topicdown(String out_trade_no,String title,String from,Long userid,Long id,String cash,BigDecimal mount,String trade_no,Integer state)
    {
        SysTopicorder sysDownorder = new SysTopicorder();
        sysDownorder.setOrderid(out_trade_no);
        sysDownorder.setTitle(title);
        sysDownorder.setFrom("1");
        sysDownorder.setUserid(userid);
        sysDownorder.setTopicid(id);
        sysDownorder.setCash(cash);
        sysDownorder.setTradeno(trade_no);
        sysDownorder.setState(1);
        iSysTopicorderService.insertSysTopicorder(sysDownorder);
        List<SysTradeset> sysTradesets = iSysTradesetService.selectSysTradesetList(new SysTradeset());
        SysTopic sysDoc = iSysTopicService.selectSysTopicByTopicid(id);
        if(sysTradesets.size()>0&&sysTradesets.get(0).getToauth2()>0) {
            SysGlodpot glodpot = new SysGlodpot();

            glodpot.setUserid(sysDoc.getUserid()); //付给文档作者的
            glodpot.setLinkid(id);

            glodpot.setGlods(mount.multiply(BigDecimal.valueOf(1 - sysTradesets.get(0).getRate())));
            glodpot.setType(52l);
            iSysGlodpotService.insertSysGlodpot(glodpot);
            iSysMemberService.updateGlod(sysDoc.getUserid(), mount.multiply(BigDecimal.valueOf(1 - sysTradesets.get(0).getRate())));
        }
        SysGlodpot glodpot = new SysGlodpot();
        glodpot.setUserid(userid);
        glodpot.setLinkid(id);

        glodpot.setGlods(BigDecimal.ZERO.subtract(mount));
        glodpot.setType(-52l);
        iSysGlodpotService.insertSysGlodpot(glodpot);
        //更新专题作者奖励
    }
    //判断文档订单是否支付
    @RequestMapping(value = "/docpaystate.htm", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String docpaystate(HttpServletRequest request,HttpServletResponse response,@RequestParam("docid") long docid,@RequestParam("type") String type,@RequestParam("readdown") String readdown) {
        long userid = -1;
        if(ShiroUtils.getSubject().getPrincipal() == null) {
            if (!(StringUtils.getCookie(request, "userid")).isEmpty())
                userid = Long.parseLong(StringUtils.getCookie(request, "userid"));
        }
        else
        {
            userid = ShiroUtils.getSysMember().getUserid().intValue();
        }
        SysDownorder sysDownorder = new SysDownorder();
        sysDownorder.setUserid(userid);
        sysDownorder.setDocid(docid);
        sysDownorder.setReaddown(readdown);
        List<SysDownorder> sysDownorderList = iSysDownorderService.selectSysDownorderList(sysDownorder);
        String orderid = "" ;
        if(sysDownorderList.size()>0)
            orderid = sysDownorderList.get(0).getOrderid();
        System.out.println(orderid+"order");
        return orderid;
    }
    //判断文档订单是否支付
    @RequestMapping(value = "/topicpaystate.htm", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String topicpaystate(HttpServletRequest request,HttpServletResponse response,@RequestParam("docid") long docid,@RequestParam("type") String type,@RequestParam("readdown") String readdown) {
        long userid = -1;
        if(ShiroUtils.getSubject().getPrincipal() == null) {
            if (!(StringUtils.getCookie(request, "userid")).isEmpty())
                userid = Long.parseLong(StringUtils.getCookie(request, "userid"));
        }
        else
        {
            userid = ShiroUtils.getSysMember().getUserid();
        }
        SysTopicorder sysDownorder = new SysTopicorder();
        sysDownorder.setUserid(userid);
        sysDownorder.setTopicid(docid);
        List<SysTopicorder> sysDownorderList = iSysTopicorderService.selectSysTopicorderList(sysDownorder);
        String orderid = "" ;
        if(sysDownorderList.size()>0)
            orderid = sysDownorderList.get(0).getOrderid();
        System.out.println(orderid+"order");
        return orderid;
    }
    //
    @GetMapping("/doc/payread/{docid}")
    @ResponseBody
    public int payread(HttpServletRequest request,@PathVariable("docid")long docid){
        /*long userid = -1;
        if(ShiroUtils.getSubject().getPrincipal() == null) {
            if (!(StringUtils.getCookie(request, "userid")).isEmpty())
                userid = Long.parseLong(StringUtils.getCookie(request, "userid"));
        }
        else
        {
            userid = ShiroUtils.getSysMember().getUserid().intValue();
        }
        SysDownorder sysDownorder = new SysDownorder();
        sysDownorder.setUserid(userid);
        sysDownorder.setDocid(docid);
        sysDownorder.setReaddown("readpay");
        List<SysDownorder> sysDownorderList = iSysDownorderService.selectSysDownorderList(sysDownorder);
        int orderid = 0 ;
        if(sysDownorderList.size()>0)
             orderid = 4;
        return orderid;*/
        SysDoc sysDoc = iSysDocService.selectSysDocByDocid(docid);
        if(sysDoc!=null) {
            long userid = -1;
            SysMember user = new SysMember();
            if (ShiroUtils.getSubject().getPrincipal() == null) {
                if (!(StringUtils.getCookie(request, "userid")).isEmpty()) {
                    userid = Long.parseLong(StringUtils.getCookie(request, "userid"));
                }
                user.setUserid(userid);
                user.setGroupid(0l);
                user.setVgroupid(0l);
                user.setGlods(0f);
            } else {
                user = iSysMemberService.selectSysMemberByUserid(ShiroUtils.getSysMember().getUserid());
            }
            //判断是否是自己的文档
            if (sysDoc.getUserid() == user.getUserid()) //自己的文档
                return 3;
            //判断是否付费下载过
            SysTradeset sysTradeset = iSysTradesetService.selectSysTradesetList(new SysTradeset()).get(0);
            Long paydue = sysTradeset.getPaydue();
            List<Long> typeids = new ArrayList<>(Arrays.asList(-31L, -32L, -33L));
            SysGlodpot readpaylog = iSysGlodpotService.findTypeUseridLinkedDue(typeids, user.getUserid(), docid, paydue);
            typeids = new ArrayList<>(Arrays.asList(-41L, -42L, -43L));
            SysGlodpot downpaylog = iSysGlodpotService.findTypeUseridLinkedDue(typeids, user.getUserid(), docid, paydue);
            if (readpaylog != null || downpaylog!=null)
                return 4;
            //vip会员日下载上限和总下载上限
            SysVgroup vgroup = iSysVgroupService.selectSysVgroupByVgroupid(user.getVgroupid());
            SysGroup ugroup = iSysGroupService.selectSysGroupByGroupid(user.getGroupid());
            Float rate = 1f;
            Integer type = 30;
            Integer dtype = -30;
            if (vgroup != null && user.getVipdate() != null && DateUtil.compare(user.getVipdate(), DateUtil.date()) > 0) {
                rate = sysDoc.getIsvip() > 0 ? 0 : vgroup.getDiscount2().floatValue();
                type = 31;
                dtype = -31;
            }
            //是否游客下载
            if (!StringUtils.contains(ugroup.getRights(), "10")) {
                if (user.getGroupid() == 0)
                    return -11;
                else
                    return -13;
            }
            Float many = (sysDoc.getDownpay().longValue()) * rate;
            if (user.getGlods() >= many) {
                //付给文档作者的
                SysGlodpot glodpot = new SysGlodpot();
                glodpot.setUserid(sysDoc.getUserid());
                glodpot.setLinkid(docid);
                glodpot.setGlods(BigDecimal.valueOf(many * (1 - sysTradeset.getRate())));
                glodpot.setType(type.longValue());
                iSysGlodpotService.insertSysGlodpot(glodpot);
                iSysMemberService.updateGlod(sysDoc.getUserid(), BigDecimal.valueOf(many * (1 - sysTradeset.getRate())));
                //这个是不是很了解
                glodpot = new SysGlodpot();
                glodpot.setUserid(user.getUserid());
                glodpot.setLinkid(docid);
                glodpot.setGlods(BigDecimal.valueOf(0 - many));
                glodpot.setType(dtype.longValue());
                iSysGlodpotService.insertSysGlodpot(glodpot);
                iSysMemberService.updateGlod(sysDoc.getUserid(), BigDecimal.valueOf(0 - many));

                return 1;
            } else {
                return -1;
            }


        }
        else
            return  -12;
    }
    //判断文档下载状态
    @PostMapping ("/doc/paydown/{docid}")
    @ResponseBody
    public int paydowndoc(HttpServletRequest request,@PathVariable("docid")long docid){

        SysDoc sysDoc = iSysDocService.selectSysDocByDocid(docid);
       if(sysDoc!=null) {
           long userid = -1;
           SysMember user = new SysMember();
           if (ShiroUtils.getSubject().getPrincipal() == null) {
               if (!(StringUtils.getCookie(request, "userid")).isEmpty()) {
                   userid = Long.parseLong(StringUtils.getCookie(request, "userid"));
               }
               user.setUserid(userid);
               user.setGroupid(0l);
               user.setVgroupid(0l);
               user.setGlods(0f);
           } else {
               user = iSysMemberService.selectSysMemberByUserid(ShiroUtils.getSysMember().getUserid());
           }
           //判断是否是自己的文档
           if (sysDoc.getUserid() == user.getUserid()) //自己的文档
               return 3;
           //判断是否付费下载过
           SysTradeset sysTradeset = iSysTradesetService.selectSysTradesetList(new SysTradeset()).get(0);
           Long paydue = sysTradeset.getPaydue();
           List<Long> typeids = new ArrayList<>(Arrays.asList(-40L, -41L, -42L));
           SysGlodpot sysGlodpot = iSysGlodpotService.findTypeUseridLinkedDue(typeids, user.getUserid(), docid, paydue);
           if (sysGlodpot != null)
               return 4;
           //vip会员日下载上限和总下载上限
           Integer daynum = iSysGlodpotService.findDayNum(typeids, user.getUserid(), true);
           Integer allnum = iSysGlodpotService.findDayNum(typeids, user.getUserid(), false);
           SysVgroup vgroup = iSysVgroupService.selectSysVgroupByVgroupid(user.getVgroupid());
           SysGroup ugroup = iSysGroupService.selectSysGroupByGroupid(user.getGroupid());
           if (vgroup != null && user.getVipdate() != null && DateUtil.compare(user.getVipdate(), DateUtil.date()) > 0 && (vgroup.getDocmoney() == -1 || vgroup.getDocmoney() >= sysDoc.getDownpay().longValue())) {
               if ((daynum > vgroup.getDowncount() || allnum > vgroup.getDowncount2()) && ugroup.getDowncount() != -1 && vgroup.getDowncount() != -1 && vgroup.getDowncount2() != -1) {
                   return -14;
               }
           } else {
               if (daynum > ugroup.getDowncount() && ugroup.getDowncount() != -1) {
                   return -14;
               }

           }
           Float rate = 1f;
           Integer type = 40;
           Integer dtype = -40;
           if (vgroup != null && user.getVipdate() != null && DateUtil.compare(user.getVipdate(), DateUtil.date()) > 0) {
               rate = sysDoc.getIsvip() > 0 ? 0 : vgroup.getDiscount2().floatValue();
               type = 41;
               dtype = -41;
           }
           //是否游客下载
           if (!StringUtils.contains(ugroup.getRights(), "11")) {
               if (user.getGroupid() == 0)
                   return -11;
               else
                   return -13;
           }
           Float many = (sysDoc.getDownpay().longValue()) * rate;
           if (user.getGlods() >= many) {
               //付给文档作者的
               SysGlodpot glodpot = new SysGlodpot();
               glodpot.setUserid(sysDoc.getUserid());
               glodpot.setLinkid(docid);
               glodpot.setGlods(BigDecimal.valueOf(many * (1 - sysTradeset.getRate())));
               glodpot.setType(type.longValue());
               iSysGlodpotService.insertSysGlodpot(glodpot);
               iSysMemberService.updateGlod(sysDoc.getUserid(), BigDecimal.valueOf(many * (1 - sysTradeset.getRate())));
               //这个是不是很了解
               glodpot = new SysGlodpot();
               glodpot.setUserid(user.getUserid());
               glodpot.setLinkid(docid);
               glodpot.setGlods(BigDecimal.valueOf(0 - many));
               glodpot.setType(dtype.longValue());
               iSysGlodpotService.insertSysGlodpot(glodpot);
               iSysMemberService.updateGlod(sysDoc.getUserid(), BigDecimal.valueOf(0 - many));

               return 1;
           } else {
               return -1;
           }


       }
       else
           return  -12;
    }
    @PostMapping ("/topic/paydown/{topicid}")
    @ResponseBody
    public int paydowntopic(HttpServletRequest request,@PathVariable("topicid")long topicid){
       /* long userid = -1;
        if(ShiroUtils.getSubject().getPrincipal() == null) {
            if (!(StringUtils.getCookie(request, "userid")).isEmpty())
                userid = Long.parseLong(StringUtils.getCookie(request, "userid"));
        }
        else
        {
            userid = ShiroUtils.getSysMember().getUserid();
        }
        //判断是否是自己的文档
        SysTopic sysTopic = iSysTopicService.selectSysTopicByTopicid(topicid);
        if(sysTopic.getUserid()==userid)
            return  3;
        SysTopicorder sysTopicorder = new SysTopicorder();
        sysTopicorder.setUserid(userid);
        sysTopicorder.setTopicid(topicid);
        List<SysTopicorder> sysTopicorderList = iSysTopicorderService.selectSysTopicorderList(sysTopicorder);
        int orderid = 0 ;
        if(sysTopicorderList.size()>0)
            orderid = 4;
        return orderid;*/
        SysTopic sysTopic = iSysTopicService.selectSysTopicByTopicid(topicid);
        if(sysTopic!=null) {
            long userid = -1;
            SysMember user = new SysMember();
            if (ShiroUtils.getSubject().getPrincipal() == null) {
                if (!(StringUtils.getCookie(request, "userid")).isEmpty()) {
                    userid = Long.parseLong(StringUtils.getCookie(request, "userid"));
                }
                user.setUserid(userid);
                user.setGroupid(0l);
                user.setVgroupid(0l);
                user.setGlods(0f);
            } else {
                user = iSysMemberService.selectSysMemberByUserid(ShiroUtils.getSysMember().getUserid());
            }
            //判断是否是自己的文档
            if (sysTopic.getUserid() == user.getUserid()) //自己的文档
                return 3;
            //判断是否付费下载过
            SysTradeset sysTradeset = iSysTradesetService.selectSysTradesetList(new SysTradeset()).get(0);
            Long paydue = sysTradeset.getPaydue();
            List<Long> typeids = new ArrayList<>(Arrays.asList(-50L, -51L, -52L));
            SysGlodpot sysGlodpot = iSysGlodpotService.findTypeUseridLinkedDue(typeids, user.getUserid(), topicid, paydue);
            if (sysGlodpot != null)
                return 4;
            //vip会员日下载上限和总下载上限
            typeids = new ArrayList<>(Arrays.asList(-40L, -41L, -42L));
            Integer daynum = iSysGlodpotService.findDayNum(typeids, user.getUserid(), true);
            Integer allnum = iSysGlodpotService.findDayNum(typeids, user.getUserid(), false);
            SysVgroup vgroup = iSysVgroupService.selectSysVgroupByVgroupid(user.getVgroupid());
            SysGroup ugroup = iSysGroupService.selectSysGroupByGroupid(user.getGroupid());
            if (vgroup != null && user.getVipdate() != null && DateUtil.compare(user.getVipdate(), DateUtil.date()) > 0 && (vgroup.getDocmoney() == -1 || vgroup.getDocmoney() >= sysTopic.getDownpay().longValue())) {
                if ((daynum > vgroup.getDowncount() || allnum > vgroup.getDowncount2()) && ugroup.getDowncount() != -1 && vgroup.getDowncount() != -1 && vgroup.getDowncount2() != -1) {
                    return -14;
                }
            } else {
                if (daynum > ugroup.getDowncount() && ugroup.getDowncount() != -1) {
                    return -14;
                }

            }
            Float rate = 1f;
            Integer type = 50;
            Integer dtype = -50;
            if (vgroup != null && user.getVipdate() != null && DateUtil.compare(user.getVipdate(), DateUtil.date()) > 0) {
                rate = sysTopic.getIsvip() > 0 ? 0 : vgroup.getDiscount2().floatValue();
                type = 51;
                dtype = -51;
            }
            //是否游客下载
            if (!StringUtils.contains(ugroup.getRights(), "41")) {
                if (user.getGroupid() == 0)
                    return -11;
                else
                    return -13;
            }
            Float many = (sysTopic.getDownpay().longValue()) * rate;
            if (user.getGlods() >= many) {
                //付给文档作者的
                SysGlodpot glodpot = new SysGlodpot();
                glodpot.setUserid(sysTopic.getUserid());
                glodpot.setLinkid(topicid);
                glodpot.setGlods(BigDecimal.valueOf(many * (1 - sysTradeset.getRate())));
                glodpot.setType(type.longValue());
                iSysGlodpotService.insertSysGlodpot(glodpot);
                iSysMemberService.updateGlod(sysTopic.getUserid(), BigDecimal.valueOf(many * (1 - sysTradeset.getRate())));
                //这个是不是很了解
                glodpot = new SysGlodpot();
                glodpot.setUserid(user.getUserid());
                glodpot.setLinkid(topicid);
                glodpot.setGlods(BigDecimal.valueOf(0 - many));
                glodpot.setType(dtype.longValue());
                iSysGlodpotService.insertSysGlodpot(glodpot);
                iSysMemberService.updateGlod(sysTopic.getUserid(), BigDecimal.valueOf(0 - many));

                return 1;
            } else {
                return -1;
            }
        }
        else
            return  -12;
    }

}
